package com.koylu.faces.security;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.regex.Pattern;

import com.koylu.faces.security.user.Group;
import com.koylu.faces.security.user.User;

public class AccessRule {
	
	private String  name;
	private boolean _private = true;
	private List    groups;
	
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public boolean isPrivate() {
		return _private;
	}
	public void setPrivate(boolean _private) {
		this._private = _private;
	}
	public List getGroups() {
		return groups;
	}
	public void setGroups(List groups) {
		this.groups = groups;
	}
	
	public void addGroup(AccessGroup group){
		if(groups == null){
			groups = new ArrayList();
		}
		groups.add(group);
	}
	
	private String namePattern;
	
	public boolean check(String name){
		if(this.name == null){
			return false;
		}
		if(namePattern == null){
			namePattern = this.name == null?"":this.name;
			if(namePattern.endsWith("*")){
				namePattern = namePattern.replaceFirst("\\*",".\\*(.jsp|.jspx|.xhtml)\\$");
			}
		}
		return Pattern.compile(namePattern).matcher(name).matches();
	}
	
	/*public List getCommonGroups(User user){
		List commonGroups = new ArrayList();
		if(user != null && user.getGroups() != null && groups !=null){
			for(int k=0;k<user.getGroups().size();k++){
				for(int i=0;i<groups.size();i++){
					Group accessGroup = (Group)groups.get(i);
					Group userGroup  = (Group)user.getGroups().get(k);
					if(userGroup.check(accessGroup)){
						commonGroups.add(accessGroup);
					}
				}
			}
		}
		return commonGroups;
	}*/	

	public boolean checkGroups(User user){
		if(user != null && user.getGroups() != null && groups !=null){
			for(int k=0;k<user.getGroups().size();k++){
				for(int i=0;i<groups.size();i++){
					Group accessGroup = (Group)groups.get(i);
					Group userGroup  = (Group)user.getGroups().get(k);
					if(userGroup.check(accessGroup)){
						return true;
					}
				}
			}
		}
		return false;
	}	
	
	public Set getAccessRights(User user){
		Set rights = new HashSet();;
		if(user !=null && user.getGroups() != null && groups != null){			
			for(int k=0;k<user.getGroups().size();k++){
				for(int i=0;i<groups.size();i++){
					AccessGroup accessGroup = (AccessGroup)groups.get(i);
					Group userGroup = (Group)user.getGroups().get(k);
					if(userGroup.check(accessGroup)){
						List _rights = accessGroup.getRights();
						if(_rights != null){
							for(int j = 0;j<_rights.size();j++){
								rights.add(((AccessRight)_rights.get(j)).getName());
							}
						}
					}
				}
			}
		}
		return rights;
	}
	
	public String toString() {		
		return name;//ToStringBuilder.reflectionToString(this,ToStringStyle.MULTI_LINE_STYLE);
	}	
	
}
